import { useEffect, useState } from 'react'
import { Form, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useRecoilValue } from 'recoil'
import {
  cityBottomConfigType,
  cityTopConfigType,
  cityTopValueType,
  cityMocalConfigType,
  isCityModal,
  hospitalTopConfigType,
  hospitalBottomConfigType,
  inpatientWardTopConfigType,
  inpatientWardBottomConfigType,
  topConfigDataType,
  pagingType,
  tableInterface,
} from '../interface/index'
import { userInfo } from '@/store/userInfo'
import {
  getRegionData,
  getYearSelect,
  getList,
  addCityAdmin,
  getModalRegion,
  editCityAdmin,
  deleteCityAdmin,
  getWordSelector,
  exportAdminInfoExcel,
} from '../service/service'
import { isNullData, convertToAntdData, findNamesByIds, exportData } from '@/utils'
import CityComponents from '../components/cityComponent/top'
import HospitalComponents from '../components/hospitalComponent/top'
import InpatientWardComponents from '../components/inpatientWardComponent/top'
// import { ExportExcel } from '@/utils/export'

export default () => {
  // 获取角色信息（ 主要是为了拿到角色的 type ）
  const userInfoData = useRecoilValue(userInfo)

  const arr = [
    { key: '20', children: <CityComponents />, label: '市级管理员' },
    { key: '30', children: <HospitalComponents />, label: '医院管理员' },
    { key: '40', children: <InpatientWardComponents />, label: '病区管理员' },
  ]

  // 表格数据
  const [tableData, setTbaleData] = useState<tableInterface[]>([])
  // 表格勾选拿到的每一条数据ID
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('选中的序号集合: ', newSelectedRowKeys)
    setSelectedRowKeys(newSelectedRowKeys)
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  // 分页信息
  const [paging, setPagin] = useState<pagingType>({
    pageSize: 10,
    pageIndex: 1,
    totalCount: 0,
  })

  // 市级管理员地区三级下拉框
  const [cityCascader, setCityCascader] = useState([])

  // 顶部地区级联数据 ( 医院管理员和病区管理员 )
  const [topRegionSelectData, setTopRegionSelectData] = useState([])

  // 顶部登录次数下拉框数据
  const [topSelectorData, setTopSelectorData] = useState([])

  // 市级弹框的目录结构
  const [cityModalRegion, setCityModalRegion] = useState([])

  // 顶部下拉框和 Input 框的值
  const [topSearchValue, setTopSearchValue] = useState<cityTopValueType>({
    region: [],
    loginTime: '', // 根据年份查询的登录次数
    inputValue: '',
    // state: '', // 状态，暂时没有
  })

  // 病区下拉框
  const [inpatientWard, setInpatientWard] = useState([])

  // 跳转路由
  const pushRouter = useNavigate()

  // 过滤管理员可以看到的 tabs 栏目
  const filterArr = arr.filter((item) => Number(item.key) > userInfoData.accountType)

  // // 关联tabs
  // const [tabsKey, setTabsKey] = useState<string>(filterArr[0].key)

  // 关联tabs
  const [tabsKey, setTabsKey] = useState<string>(filterArr.length > 0 ? filterArr[0].key : '')

  // 病区的名字
  const [word, setWord] = useState('')

  // 获取表格数据
  const getTable = async (pageIndex?: number) => {
    const params = {
      pageSize: paging.pageSize,
      pageIndex: pageIndex || paging.pageIndex,
      search: {
        searchMax: topSearchValue.inputValue || '', // input 输入框内容查询
        areaIdFilter: topSearchValue.region[topSearchValue.region.length - 1] || '', // 地区查询
        accountType: tabsKey,
        year: topSearchValue.loginTime || '', // 年份查询
        inpatientWardTypeName: word || '', // 病区名字
      },
      searchCount: true,
    }
    const res = await getList(params)
    if (isNullData(res)) {
      setPagin({ ...paging, totalCount: res.data.totalCount, pageIndex: 1, pageSize: 10 })
      setTbaleData(res.data.items)

      // if (res.data.items.length === 0) {
      //   setPagin({ ...paging, pageIndex: 1 })
      // }

      res.data.items.forEach((item: any) => {
        // 此处将后端返回的三个地区转换成一个 去除掉为 null的（市级地区只有两级） 变成新数组在 cloumn 中转换文字
        const region = [item.provinceId, item.cityId, item.areaId]
        const filteredArray = region.filter((item) => item !== null)
        item.regions = filteredArray
      })
    }
    console.log('🦢🦢表格数据', res.data)
  }

  // 获取病区
  const getWard = (value: any) => {
    console.log('🦢🦢', value)
    if (value === undefined) {
      setWord('')
      return
    }
    setWord(value[1])
  }
  // todo 切换 tabs 事件
  const changeTabs = (value: string) => {
    setSelectedRowKeys([]) // 清空存储的ids
    setTabsKey(value)
    setTopSearchValue({ ...topSearchValue, loginTime: '', region: '', inputValue: '' })
  }

  // todo 获取市级弹框目录结构
  const getCityModalRegion = async () => {
    const res = await getModalRegion()
    if (isNullData(res)) {
      const cityModalRegionDatas = convertToAntdData(res.data)
      setCityModalRegion(cityModalRegionDatas)
    }
  }

  // 市级管理员 city
  // #region
  const [cityForm] = Form.useForm()

  // 市弹框控制
  const [cityisModalOpen, setCityIsModalOpen] = useState<boolean>(false)
  // 控制 新增(1)，编辑(2),查看(3)
  const [cityModalType, setCityModalType] = useState(isCityModal.ADD)
  // 存放查看和编辑的数据
  const [cityLookEditData, setCityLookEditData] = useState<any>({})

  // 获取地区下拉框值
  const getAreaSelectValue = (value: any) => {
    if (value === undefined) {
      setTopSearchValue({ ...topSearchValue, region: '' })
    } else {
      setTopSearchValue({ ...topSearchValue, region: value })
    }
  }
  // 获取登录次数下拉框值
  const getLoginTimeSelectValue = (value: string) => {
    setTopSearchValue({ ...topSearchValue, loginTime: value })
  }

  // 负责人姓名/手机 搜索框值
  const getInputNamePhoneValue = (e: any) => {
    setTopSearchValue({ ...topSearchValue, inputValue: e.target.value })
  }
  // input 回车事件
  const inputEnter = () => {
    getTable()
  }

  // 新增管理员打开弹框
  const addAdmin = () => {
    setCityIsModalOpen(true)
    setCityModalType(isCityModal.ADD)
  }
  // 关闭新增弹框
  const cityhandleCancel = () => {
    setCityIsModalOpen(false)
    cityForm.resetFields()
  }
  // 市查看事件
  const cityLook = (record: any) => {
    record.regions = findNamesByIds(topRegionSelectData, record.regions).join('/')
    pushRouter('/user-admin-province/cityExamine', { state: record })
  }
  // 市编辑事件
  const cityEdit = (record: any) => {
    setCityLookEditData(record)
    setCityIsModalOpen(true)
    setCityModalType(isCityModal.EDIT)

    // 拆分护理部电话
    const splitNursingPhone = record.telphone.split('-')

    // 拼接省和市
    const jointRegion = [record.provinceId, record.cityId]
    console.log('🦢🦢', jointRegion)
    cityForm.setFieldsValue({
      areaId: jointRegion,
      name: record.username,
      phone: record.phone,
      areaCode: splitNursingPhone[0],
      phoneCode: splitNursingPhone[1],
      email: record.email,
    })
  }

  // 市弹框确认按钮
  const cityOnFinish = async (value: any) => {
    // 新增
    if (cityModalType === 1) {
      value.areaId = value.areaId.join(',') // 地区
      value.telphone = `${value.areaCode}-${value.phoneCode}` // 拼接护理部电话
      delete value.areaCode // 删除自定义的区号属性
      delete value.phoneCode // 删除自定义的区号-手机号属性
      const res = await addCityAdmin(value)
      if (isNullData(res) && res.data.status) {
        message.success('新增成功')
        getTable()
        setCityIsModalOpen(false)
      } else {
        message.info(res.data.msg)
      }
    }

    // 编辑
    if (cityModalType === 2) {
      value.id = cityLookEditData.id
      value.areaId = value.areaId.join(',') // 地区
      value.telphone = `${value.areaCode}-${value.phoneCode}` // 拼接护理部电话
      delete value.areaCode // 删除自定义的区号属性
      delete value.phoneCode // 删除自定义的区号-手机号属性
      const res = await editCityAdmin(value)
      console.log('🦢🦢', res)
      if (isNullData(res) && res.data.status) {
        message.success('编辑成功')
        getTable()
        setCityIsModalOpen(false)
      } else {
        message.error(res.data.msg)
      }
    }
  }

  // 市级删除
  const cityDeleteData = async (record: any) => {
    const res = await deleteCityAdmin({ id: record.id })
    if (isNullData(res)) {
      message.success('删除成功')
      if (tableData.length === 1) {
        getTable(1)
        setPagin({ ...paging, pageIndex: 1 })
      } else {
        getTable()
      }
    }
  }
  // #endregion

  // 医院管理员 hospital
  // #region

  // 医院管理员导出事件
  // todo accountType 写死，导出医院管理员的
  const hospitalExport = async () => {
    const tableIds = tableData.reduce((acc: any, cur: any) => {
      acc.push(cur.id)
      return acc
    }, [])

    if (selectedRowKeys.length === 0) {
      const params = {
        accountType: 30,
        ids: tableIds,
      }
      const res = await exportAdminInfoExcel(params)
      const title = '医院管理员全部数据'
      exportData(res, title, 'xlsx')
      console.log('🦢🦢', res)
      return
    }

    if (selectedRowKeys.length > 0) {
      const params = {
        accountType: 30,
        ids: selectedRowKeys,
      }
      const res = await exportAdminInfoExcel(params)
      const title = '医院管理员部分数据'
      exportData(res, title, 'xlsx')
    }
  }

  // 医院表格查看事件
  const hospitalExamine = (record: any) => {
    // console.log('🦢🦢', findNamesByIds(topRegionSelectData, record.regions))
    record.regions = findNamesByIds(topRegionSelectData, record.regions).join('/')
    pushRouter('/user-admin-province/hospitalExamine', { state: record })
  }

  // #endregion

  // 病区管理员 inpatientWard
  // #region
  // 病区导出事件
  // todo accountType 写死，导出病区管理员的
  const inpatientWardExport = async () => {
    const tableIds = tableData.reduce((acc: any, cur: any) => {
      acc.push(cur.id)
      return acc
    }, [])

    if (selectedRowKeys.length === 0) {
      const params = {
        accountType: 40,
        ids: tableIds,
      }
      const res = await exportAdminInfoExcel(params)
      const title = '病区管理员全部数据'
      exportData(res, title, 'xlsx')
      console.log('🦢🦢', res)
      return
    }

    if (selectedRowKeys.length > 0) {
      const params = {
        accountType: 40,
        ids: selectedRowKeys,
      }
      const res = await exportAdminInfoExcel(params)
      const title = '病区管理员部分数据'
      exportData(res, title, 'xlsx')
    }
  }
  // 病区管理员查看事件
  const inpatientWardExamine = (record: any) => {
    console.log(record)
    record.regions = findNamesByIds(topRegionSelectData, record.regions).join('/')
    pushRouter('/user-admin-province/inpatientWardExamine', { state: record })
  }
  // #endregion

  // 单独过滤市级的三级联动下拉框函数 ( 过滤成两级 )
  const filterData = (data: any) =>
    data.map((item: any) => {
      const { id, name, children } = item
      const filteredItem = {
        value: id,
        label: name,
      }
      if (children && children.length > 0) {
        const filteredChildren = children.map((childItem: any) => {
          const { id: childId, name: childName } = childItem
          return {
            value: childId,
            label: childName,
          }
        })
        filteredItem.children = filteredChildren
      }
      return filteredItem
    })
  // 获取顶部地区管理员下拉框
  const getRegionProvice = async () => {
    // 判断省级管理员 市管理员
    let ifId: any = 0
    if (userInfoData.accountType === 10) {
      ifId = userInfoData.provinceId
    }
    if (userInfoData.accountType === 20) {
      ifId = userInfoData.cityId
    }
    const res = await getRegionData({ signUserLocationId: ifId })

    if (isNullData(res)) {
      const reconsitutionData = convertToAntdData(res.data)
      setTopRegionSelectData(reconsitutionData) // 医院和病区的三级联动数据
      setCityCascader(filterData(res.data)) // 市级的三级联动数据
      console.log('🦢🦢', filterData(res.data))
    }
  }
  // 获取年份下拉框
  const getYearSelector = async () => {
    const res = await getYearSelect()
    const yearSelect = res.data?.reduce((acc: any, cur: any) => {
      acc.push({ value: cur, label: cur })
      return acc
    }, [])
    console.log('🦢🦢', yearSelect)
    setTopSelectorData(yearSelect)
  }

  // 洗 bbj word
  const transformToCascaderData = (data: any) =>
    data.map((department: any) => {
      const cascaderItem = {
        value: department.unit,
        label: department.unit,
      }

      if (department.children && department.children.length > 0) {
        cascaderItem.children = transformToCascaderData(department.children)
      }

      return cascaderItem
    })
  // 获取病区管理员的病区下拉接口
  const getWordSele = async () => {
    const res = await getWordSelector()
    const data = transformToCascaderData(res.data)
    setInpatientWard(data)
  }

  // 分页切换
  const changePagingUploadTable = (page: number, pageSizes: number) => {
    setPagin({
      ...paging,
      pageIndex: page,
      pageSize: pageSizes,
    })
  }

  useEffect(() => {
    getRegionProvice() // 获取顶部地区三联结构
    getYearSelector() // 获取登录次数（年份）下拉框数据结构
    // getTable() // 获取表格数据
    getCityModalRegion() // 获取市级弹框的目录结构
    getWordSele()
  }, [])

  // 页码更新触发表格重新查询
  useEffect(() => {
    getTable()
  }, [paging.pageIndex, word, paging.pageSize, topSearchValue.loginTime, topSearchValue.region, tabsKey])

  // 市级管理员
  // #region
  const cityTopConfig: cityTopConfigType = {
    getAreaSelectValue,
    getLoginTimeSelectValue,
    getInputNamePhoneValue,
    inputEnter,
    addAdmin,
    getWard,
    cityhandleCancel,
    paging,
    changePagingUploadTable,
    cityCascader,
  }

  const cityMocalConfig: cityMocalConfigType = {
    cityisModalOpen,
    cityModalType,
    cityForm,
    cityOnFinish,
    cityModalRegion,
  }

  const cityBottomConfig: cityBottomConfigType = {
    cityLook,
    cityEdit,
    cityDeleteData,
  }
  // #endregion

  // 医院管理员
  // #region
  const hospitalTopConfig: hospitalTopConfigType = {
    hospitalExport,
  }

  const hospitalBottomConfig: hospitalBottomConfigType = {
    hospitalExamine,
  }
  // #endregion

  // 病区管理员
  // #region
  const inpatientWardTopConfig: inpatientWardTopConfigType = {
    inpatientWardExport,
  }

  const inpatientWardBottomConfig: inpatientWardBottomConfigType = {
    inpatientWardExamine,
  }
  // #endregion

  // 顶部所需配置数据
  const topConfigData: topConfigDataType = {
    changeTabs, // 切换 tabs 事件
    topRegionSelectData, // 三级联动地区数据
    topSelectorData, // 登录次数查询数据
    tabsKey,
    filterArr,
    inpatientWard,
    rowSelection,
  }

  // 表格数据配置
  const tableConfig = {
    tableData,
  }
  return {
    cityTopConfig,
    cityMocalConfig,
    cityBottomConfig,

    hospitalTopConfig,
    hospitalBottomConfig,

    inpatientWardTopConfig,
    inpatientWardBottomConfig,
    topConfigData,
    tableConfig,
  }
}
